package com.saltedfish.tool.ui.achievement

import android.Manifest
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.room.Room
import androidx.room.RoomDatabase
import cn.droidlover.xdroidmvp.base.SimpleListener
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.log.XLog
import cn.droidlover.xdroidmvp.mvp.XFragment
import cn.droidlover.xdroidmvp.router.Router
import cn.droidlover.xdroidmvp.util.AppUtil
import com.blankj.rxbus.RxBus
import com.saltedfish.tool.R
import com.saltedfish.tool.constant.StringConstant
import com.saltedfish.tool.dao.AppDatabase
import com.saltedfish.tool.dialog.UICreateFlagDialog
import com.saltedfish.tool.model.FlagTable
import com.saltedfish.tool.model.ModelInfo
import com.saltedfish.tool.model.SmallTable
import com.saltedfish.tool.present.XFP
import com.saltedfish.tool.ui.flag.FlagDetailActivity
import com.saltedfish.tool.util.ViewClickUtils
import com.tencent.wcdb.database.SQLiteCipherSpec
import com.tencent.wcdb.room.db.WCDBOpenHelperFactory
import kotlinx.android.synthetic.main.fragment_achievement.*
import kotlinx.android.synthetic.main.fragment_achievement.btn_create
import kotlinx.android.synthetic.main.fragment_achievement.mRecyclerView

class FragmentAchievement : XFragment<XFP>(), View.OnClickListener {

    companion object {
        fun newInstance(): FragmentAchievement {
            return FragmentAchievement()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_achievement
    }

    override fun initData(savedInstanceState: Bundle?) {
        initRoom()
        BusProvider.getBus().subscribe(context,
            RxBus.Callback<ModelInfo> { modelInfo ->
                if(modelInfo !=null && modelInfo.updateFlag){
                    initDataShow()
                }
            })
    }

    override fun loadData() {
        super.loadData()
        showTopData()
    }

    //显示顶部数据资源
    private fun showTopData() {
       ViewClickUtils.setViewClick(this, btn_create)
        initDataShow()
    }

    override fun newP(): XFP? {
        return null
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_create -> {
                checkStoragePermission()
            }

        }
    }


    //检查相关权限
    private fun checkStoragePermission() {
        if (
            rxPermissions.isGranted(Manifest.permission.READ_CALENDAR)
            && rxPermissions.isGranted(Manifest.permission.WRITE_CALENDAR)
            && rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
            && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        ) {
            initCreateFalgView()
        } else {
            rxPermissions.request(
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.WRITE_CALENDAR,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
            ).subscribe { t ->
                if (t) {
                    initCreateFalgView()
                }
            }.isDisposed
        }

    }


    override fun onResume() {
        super.onResume()
        initDataShow()
    }

    private var database: AppDatabase? = null
    private var linearLayoutManager: LinearLayoutManager? = null
    private var adapter: AchievementAdapter? = null
    private var flagInfoLists: MutableList<FlagTable> = ArrayList()
    private var showFlagLists: MutableList<FlagTable> = ArrayList()


    private fun  initDataShow(){
        flagInfoLists.clear()
        showFlagLists.clear()

        if(database !=null){
            var infoDao = database!!.flagInfoDao()
            var subFlagModelDao = database!!.subFlagDao()
            mLinearHaveFlag.visibility = View.GONE
            flagInfoLists = infoDao!!.all
            adapter = AchievementAdapter(showFlagLists)
            mRecyclerView.adapter = adapter

            if(flagInfoLists.size == 0){
                mLinearNoFlag.visibility = View.VISIBLE
            }else{
                mLinearNoFlag.visibility = View.GONE
                var subFlagLists: MutableList<SmallTable> = ArrayList()

                for (item in flagInfoLists){
                    var subFlagList = subFlagModelDao!!.getAllByFlagIdAndProgress(item.flagId,1.0f,"提前完成")
                  //  XLog.e("${item}-----subFlagLists----->>${subFlagList}")
                    if(subFlagList !=null && subFlagList.size !=0){
                        subFlagLists.addAll(subFlagList)
                        showFlagLists.add(item)
                    }
                }

                if(subFlagLists.size == 0){
                    mLinearHaveFlag.visibility = View.VISIBLE
                }else{
                    mLinearHaveFlag.visibility = View.GONE
                    linearLayoutManager = LinearLayoutManager(context)
                    mRecyclerView.layoutManager = linearLayoutManager
                    adapter!!.setSubFlagModelDao(subFlagModelDao)

                    adapter!!.setListener(object : SimpleListener<String>() {
                        override fun onClick(flagId: String) {
                            // initCreateSonFalgView(flagId)
                        }
                        override fun onClick(flagId: String, str: String) {
                            Router.newIntent(context)
                                    .putString("flagId", flagId)
                                    .to(FlagDetailActivity::class.java).launch()
                        }
                    })
                }

            }
        }



    }

    private fun initRoom() {
        val cipherSpec = SQLiteCipherSpec()
            .setPageSize(4096)
            .setKDFIteration(64000)
        val factory =
            WCDBOpenHelperFactory() //  .passphrase("passphrase".getBytes())  // passphrase to the database, remove this line for plain-text
                .cipherSpec(cipherSpec) // cipher to use, remove for default settings
               //  .writeAheadLoggingEnabled(false)       // enable WAL mode, remove if not needed
                .asyncCheckpointEnabled(true) // enable asynchronous checkpoint, remove if not needed
        database = Room.databaseBuilder(
            context,
            AppDatabase::class.java, StringConstant.DbBase
        )
            .allowMainThreadQueries()
            .setJournalMode(RoomDatabase.JournalMode.TRUNCATE)
            .openHelperFactory(factory) // specify WCDBOpenHelperFactory when opening database
            .build()
    }


    private var  createFlagDialog : UICreateFlagDialog? =null
    private val mHandler = Handler()

    /**
     * 创建Flag
     */
    private fun initCreateFalgView() {

      //  if (createFlagDialog == null) {
            createFlagDialog = UICreateFlagDialog(context,database)
            createFlagDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {
//                    if (type == "save") {
//                        initDataShow()
//                        createFlagDialog!!.dismiss()
//                    }
                }
            })
   //     }
        createFlagDialog!!.setOnKeyBackListener(false)
        createFlagDialog!!.show()
        mHandler.postDelayed({
            AppUtil.showSoftInput(context)
        }, 500)

    }
}